﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using WebApp.Controls;
using System.Collections.Generic;
using KDPWebPart.ControlTemplates.KDPWebPart;
using MapEntities;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using Microsoft.SharePoint.WebPartPages;

namespace KDPWebPart.MapWebPart
{
    [ToolboxItemAttribute(false)]
    public class KDPMapWebPart : System.Web.UI.WebControls.WebParts.WebPart, IWebEditable
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/KDPWebPart/KDPVisualWebPart/MapWebPartControl.ascx";
        private MapWebPartControl mapControl = null;


        [WebBrowsable(true), Personalizable(PersonalizationScope.Shared)]
        public string MapData { get; set; }
        //public MapEditorControl popupeditor;
        //private Panel ModalBackgroundPanel()
        //{
        //    Panel pnlModal = new Panel();
        //    pnlModal.ID = "pnlModal";
        //    pnlModal.Style["display"] = "none";
        //    pnlModal.Style["position"] = "absolute";
        //    pnlModal.Style["left"] = "0px";
        //    pnlModal.Style["top"] = "0px";
        //    pnlModal.Style["z-index"] = "9";
        //    pnlModal.Style["background-color"] = "#383838";
        //    pnlModal.Style["filter"] = "alpha(opacity=60)";
        //    return pnlModal;
        //}

        protected override void OnLoad(EventArgs e)
        {

            base.OnLoad(e);
        }
        //private Panel ModalSelectStoresPanel()
        //{
        //    //Panel pnlSelectStores = new Panel();
        //    //pnlSelectStores.ID = "pnlSelectStores";
        //    //pnlSelectStores.Style["display"] = "none";
        //    //pnlSelectStores.Style["position"] = "absolute";
        //    //pnlSelectStores.Style["left"] = "5px";
        //    //pnlSelectStores.Style["top"] = "5px";
        //    //pnlSelectStores.Style["z-index"] = "10";
        //    //pnlSelectStores.Style["background-color"] = "#FFFFFF";
        //    ////popupeditor = (MapDataEditor)Page.LoadControl(@"~/_CONTROLTEMPLATES/KDPWebPart/EditorFiles/MapDataEditor.ascx");
        //    //popupeditor = (MapEditorControl)Page.LoadControl(@"~/_CONTROLTEMPLATES/KDPWebPart/MapEditorControl.ascx");
        //    //popupeditor.ID = "editorWindowControl";
        //    //pnlSelectStores.Controls.Add(popupeditor);
        //    //return pnlSelectStores;

        //}

        public override void DataBind()
        {
            base.DataBind();
        }

        protected override void OnPreRender(EventArgs e)
        {
            
            base.OnPreRender(e);
            if (!Page.IsPostBack && !string.IsNullOrEmpty(MapData))
            {
                mapControl.RequestData =this.GetMapdata();
                //SPSite site = SPContext.Current.Site;
                //SPWeb web = site.OpenWeb();
                //string p = WebPartManager.ResolveUrl(Page.AppRelativeVirtualPath);
                mapControl.pageUri = Page.Request.Url.ToString();
                mapControl.BindMapData();
            }
        }

        public void SaveMapData(MapDataRequest request)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(MapDataRequest));
            StringWriter writer = new StringWriter();
            serializer.Serialize(writer, request);
            MapData = writer.ToString();
        }



        protected override void OnEditModeChanged(EventArgs e)
        {
            base.OnEditModeChanged(e);
        }

        protected override void CreateChildControls()
        {
            mapControl = (MapWebPartControl)Page.LoadControl(_ascxPath);
            Controls.Add(mapControl);
            //Controls.Add(ModalBackgroundPanel());
            //Controls.Add(ModalSelectStoresPanel());
        }

        public override EditorPartCollection CreateEditorParts()
        {
            List<EditorPart> editors = new List<EditorPart>();   
            editors.Add(new MyEditorPart(GetStorageKey().ToString()));            
            return new EditorPartCollection(editors);
        }

        public Guid GetStorageKey()
        {
            if (WebPartManager != null)
            {
                //SPSite site = SPContext.Current.Site;
                //SPWeb web = site.OpenWeb();
                //string p = WebPartManager.ResolveUrl(Page.AppRelativeVirtualPath);
                //SPFile f = web.GetFile(p);
                //SPLimitedWebPartManager mgr = f.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                //SPLimitedWebPartManager mgr = web.GetLimitedWebPartManager(
                //    p, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                return new Guid(this.ID.Remove(0, 2).Replace('_', '-'));
            }
            else return Guid.Empty;
        }

        internal MapDataRequest GetMapdata()
        {
            if (string.IsNullOrEmpty(MapData))
            {
                var entity = MapDataRequest.CreateEmpty();
                entity.Id = GetStorageKey();
                return entity;
                
            }
            else
            {
                XmlSerializer serializer = new XmlSerializer(typeof(MapDataRequest));
                StringReader reader = new StringReader(MapData);

                MapDataRequest editedRequest = (MapDataRequest)serializer.Deserialize(reader);
                editedRequest.Id = GetStorageKey();
                return editedRequest;
            }
        }
    }

    public class MyEditorPart : EditorPart
    {
        private string webPartID;
        private EditorPaneControl editorControl = null;

        protected override void CreateChildControls()
        {
            editorControl = (EditorPaneControl)Page.LoadControl(@"~/_CONTROLTEMPLATES/KDPWebPart/EditorPaneControl.ascx");
            Controls.Add(editorControl);
            base.CreateChildControls();


        }

        public KDPMapWebPart GetCurrentWebPart()
        {
            KDPMapWebPart webPart = WebPartToEdit as KDPMapWebPart;
            return webPart;
        }

        public MyEditorPart(string webPartID)
        {
            this.ID = "MyEditorPart" + webPartID;
            this.webPartID = webPartID;
        }

        public override bool ApplyChanges()
        {
            //EnsureChildControls();
            //var webPart = GetCurrentWebPart();
            //Panel p = ((Panel)webPart.FindControl("pnlSelectStores"));
            //WebApp.Controls.MapDataEditor editor = (MapDataEditor)p.Controls[0].Controls[0].FindControl("ctlMapDataEditor");
            //var mapdata = editor.EndEdit();
            //webPart.SaveMapData(mapdata);
            return true;
        }

        public override void SyncChanges()
        {
            EnsureChildControls();


            editorControl.WebPartID = webPartID;
            editorControl.Edit(webPartID);

        }

    }
}
